package edu.xhu;


import com.bean.User;
import com.constant.Constant;
import com.data.LoginEduSystemData;
import com.net.ClientError;
import com.net.LoadData;
import com.net.RequestListener;
import com.net.RequestParameter;

import edu.xhu.util.DatabaseAdapter;
import edu.xhu.util.FileManager;
import edu.xhu.view.LoadingDialog;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;

/**
 * 登录activity
 * @author swerit
 *
 */
public class LoginActivity extends Activity{

	private Button mBtnBack;
	private Button mBtnLogin;					//登录按钮
	private Button mBtnLocal;					//获取本地信息
	private EditText userIdEditText;			//用户号输入框
	private EditText pwdEditText;				//用户密码输入框
	private RadioButton teacherRadioButton, studentRadioButton;		//老师，学生单选框
	private CheckBox rememberMe;				//记住我 单选框
	
	private String userId, password;			//用户名和密码
	
	private XhuApplication application;
	
	//标志进入教师和学生教务系统的渠道，本地或是网络登录进入
	public static final String FROM_WHERE   = "from";
	public static final String FROM_WEB		= "web";
	public static final String FROM_LOCAL	= "local";
	
	private DatabaseAdapter dbAdapter;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		
		dbAdapter = new DatabaseAdapter(this);
		
		initView();
		setListener();
	}
	
	private void initView(){
		mBtnBack			= (Button) findViewById(R.id.button_back);
		mBtnLogin			= (Button) findViewById(R.id.button_login);
		userIdEditText		= (EditText) findViewById(R.id.edittext_userId);
		pwdEditText			= (EditText) findViewById(R.id.edittext_password);
		teacherRadioButton	= (RadioButton) findViewById(R.id.radiobutton_teacher);
		studentRadioButton	= (RadioButton) findViewById(R.id.radiobutton_student);
		rememberMe			= (CheckBox) findViewById(R.id.checkbox_remember_me);
		application			= (XhuApplication) getApplication();
		mBtnLocal			= (Button) findViewById(R.id.button_local_course);
		
		//恢复界面显示
		dbAdapter.openDatabase();
		User user = dbAdapter.getAccount(User.EDU_SYS);
		dbAdapter.closeDatabase();
		if (user != null){
			userIdEditText.setText(user.getUserId());
			pwdEditText.setText(user.getPassword());
			
			String name;
			int role = -1;
			
			name = user.getName();
			if (null != user.getRole() && !user.getRole().equals(""))
				role = Integer.parseInt(user.getRole());
			
			application.setRole(role);
			application.setUserName(name);
			
			if(name != null && !name.equals("")){
				rememberMe.setChecked(true);
			}
			if (role == XhuApplication.TEACHER){
				teacherRadioButton.setChecked(true);
			}
		}
	}
	
	private void setListener(){
		mBtnLogin.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				login();
			}
		});
		
		mBtnBack.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				finish();
				
				/*Intent intent = new Intent();
				intent.setClass(LoginActivity.this,XiHuaActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);*/
			}
		});
		
		mBtnLocal.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				//首先清除临时变量中的信息，保证完全退出登录
				application.setLogin(false);
				
				Intent intent = null;
				if (teacherRadioButton.isChecked()){
					application.setRole(XhuApplication.TEACHER);
					intent = new Intent(LoginActivity.this, EduTeacherIndexActivity.class);
					
				}else if (studentRadioButton.isChecked()) {
					application.setRole(XhuApplication.STUDENT);
					intent = new Intent(LoginActivity.this, StudentActivity.class);
				}
				
				intent.putExtra(FROM_WHERE, FROM_LOCAL);
				startActivity(intent);
			}
		});
	}
	
	/**
	 * 处理登录流程
	 */
	private void login(){
		userId			= userIdEditText.getText().toString();
		password		= pwdEditText.getText().toString();
		
		if (!checkInput(userId, password)){
			Toast.makeText(LoginActivity.this, "用户名和密码不能为空!", 0).show();
			return;
		}
		
		//设置角色
		if (teacherRadioButton.isChecked()){
			application.setRole(XhuApplication.TEACHER);
		}else if (studentRadioButton.isChecked()) {
			application.setRole(XhuApplication.STUDENT);
		}
		
		teacherRadioButton.post(new Runnable() {
			public void run() {
				LoadingDialog.showWindow(LoginActivity.this);
			}
		});
		
		RequestParameter parameter = new RequestParameter();
		parameter.add("TextBox1", userId);
		parameter.add("TextBox2", password);
		if (application.getRole() == XhuApplication.STUDENT){
			parameter.add("RadioButtonList1", "学生");
		}else if (application.getRole() == XhuApplication.TEACHER) {
			parameter.add("RadioButtonList1", "教师");
		}
		
		
		LoadData.loadData(Constant.LOGIN_EDU_SYSTEM_DATA, parameter, new RequestListener() {
			public void onComplete(Object obj) {
				LoginEduSystemData data = (LoginEduSystemData) obj;
				dealLoginSuccess(data);
			}
			public void onError(ClientError ed) {
				LoadingDialog.dismiss();
				ErrorShow.showError(LoginActivity.this, ed);
			}
			
		});
	}
	
	private void dealLoginSuccess(LoginEduSystemData data){
		application.setLogin(true);
		
		// 根据单选框的选择进行界面跳转
		if (application.getRole() == XhuApplication.TEACHER) {
			application.setUserIdEdu(userId);
			application.setUserName(data.getUserName());
			application.setPasswordEdu(password);
			application.setRole(XhuApplication.TEACHER);
			application.setScheduleUrl(data.getScheduleUrl());
			application.setTeaNameListUrl(data.getClassUrl());
			application.setRefererUrl(data.getReferer());
			
			// 选择“记住我”，则将用户名和密码加密保存在本地数据库中
			if (rememberMe.isChecked()) {
				/**
				 * 此处需要加密
				 */
				User user = new User();
				user.setUserId(userId);
				user.setPassword(password);
				user.setRole(application.getRole() + "");
				user.setName(data.getUserName());
				user.setPart(User.EDU_SYS);
				
				dbAdapter.openDatabase();
				dbAdapter.saveAccount(user);
				dbAdapter.closeDatabase();
			}

			// 跳转到教师教务系统
			LoadingDialog.dismiss();
			
			Intent intent = new Intent(LoginActivity.this, EduTeacherIndexActivity.class);
			intent.putExtra(FROM_WHERE, FROM_WEB);
			startActivity(intent);

		} else if (application.getRole() == XhuApplication.STUDENT) {
			application.setUserIdEdu(userId);
			application.setUserName(data.getUserName());
			application.setPasswordEdu(password);
			application.setScheduleUrl(data.getScheduleUrl());
			application.setRole(XhuApplication.STUDENT);
			application.setExamineUrl(data.getExamineUrl());
			application.setGradeUrl(data.getGradeUrl());
			application.setRefererUrl(data.getReferer());
			
			// 选择“记住我”，则将用户名和密码加密保存在本地文件中
			if (rememberMe.isChecked()) {
				/**
				 * 此处需要加密
				 */
				User user = new User();
				user.setUserId(userId);
				user.setPassword(password);
				user.setRole(application.getRole() + "");
				user.setName(data.getUserName());
				user.setPart(User.EDU_SYS);
				
				dbAdapter.openDatabase();
				dbAdapter.saveAccount(user);
				dbAdapter.closeDatabase();
			}
			
			// 跳转到学生界面
			LoadingDialog.dismiss();
			Intent intent = new Intent(LoginActivity.this, StudentActivity.class);
			intent.putExtra(FROM_WHERE, FROM_WEB);
			startActivity(intent);
		}
	}
	
	/**
	 * 对用户的输入进行检查
	 * @param userId：用户名
	 * @param pwd：登录密码
	 * @return：true-通过了检查，false-没有通过检查
	 */
	private boolean checkInput(String userId, String pwd){
		if (userId == null || userId.equals("")
			|| pwd == null || pwd.equals("")){
			
			return false;
		}
		return true;
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK){
			if (LoadingDialog.isShowing())
				LoadingDialog.dismiss();
			else {
				//finish();
				
				Intent intent = new Intent();
				intent.setClass(LoginActivity.this,XiHuaActivity.class);
				intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
				startActivity(intent);
			}
		}
		return true;
	}
}
